package com.fengmi.auth;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengmi.sso.entity.SysUser;
import com.fengmi.utils.jwt.JwtParseException;
import com.fengmi.utils.jwt.JwtUtils;
import com.fengmi.utils.jwt.RsaUtils;
import com.fengmi.vo.ResultVO;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.FileNotFoundException;
import java.security.PublicKey;
import java.util.regex.Pattern;

@Component
@RefreshScope
public class AuthFilter implements GlobalFilter, Ordered {

    //加载白名单
    @Value("${resources.white}")
    private String WHITE;



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String[] arr = WHITE.split(",");
        for (String s : arr) {
            if(Pattern.matches(s,request.getPath().toString())){
                //放行
                return  chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){

            //不能放行
           return response(response,new ResultVO(false,"非法令牌"));

        }

        //校验令牌合法性
        try {
            String path = ResourceUtils.getFile("classpath:rsa.pub").getPath();
            PublicKey publicKey = RsaUtils.getPublicKey(path);
            SysUser sysUser = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);


            //将用户信息放入请求头
            ServerHttpRequest newHttpRequest = request.mutate().header("userinfo", JSONUtil.toJsonStr(sysUser)).build();

            ServerWebExchange newExchange = exchange.mutate().request(newHttpRequest).build();

            //放行
            return  chain.filter(newExchange);

        }catch (FileNotFoundException e) {
           return response(response,new ResultVO(false,"令牌解析无效"));
        }catch (JwtParseException e){
           return response(response,new ResultVO(false,"非法令牌"));

        }catch (Exception exception){
            exception.printStackTrace();
            return response(response,new ResultVO(false,"其他异常"));
        }

    }

    @Override
    public int getOrder() {
        return -100;
    }

    private Mono<Void> response(ServerHttpResponse response, ResultVO res){
        //不能放行，直接返回，返回json信息
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());

        return response.writeWith(Flux.just(dataBuffer));//响应json数据
    }

//    public static void main(String[] args) {
//        try {
//            int i = 1/0;
//
//
//        }catch (ArithmeticException exception){
//            System.out.println("!!!!");
//        }
//    }

}
